//
//  NSURL+UtilsExtras.m
//  EVTUtils
//
//  Created by xeon well on 13/3/12.
//  Copyright (c) 2012 eightcolor, Inc. All rights reserved.
//

#import "NSURL+UtilsExtras.h"

@implementation NSURL (UtilsExtras)
+ (id)URLWithString:(NSString *)urlString paramDictionary:(NSDictionary *)paramDict {
    return [[[self class] alloc] initWithString:urlString paramDictionary:paramDict];
}

- (id)initWithString:(NSString *)urlString paramDictionary:(NSDictionary *)paramDict {
    if (urlString == nil) return nil;
    if (paramDict == nil || [paramDict count] == 0) return [self initWithString:urlString];
    ///TODO:加入对URL中#号部分的判断
    NSMutableString *result = [NSMutableString stringWithString:urlString];
    NSString *endString = @"";
    
    //判断是否包含“#”
    if (!([result rangeOfString:@"#"].location == NSNotFound)) {
        NSArray *resultArray = [result componentsSeparatedByString:@"#"];
        if (resultArray.count > 0) {
            result = [resultArray objectAtIndex:0];
        }

        endString = [NSString stringWithFormat:@"#%@",(resultArray.count > 1)?[resultArray objectAtIndex:1]:nil];
    }
    [result appendString:(!([result rangeOfString:@"?"].location == NSNotFound)) ? @"&" : @"?"];
    
    NSMutableArray *paramsArray = [[NSMutableArray alloc] initWithCapacity:[paramDict count]];
    NSEnumerator *enumerator = [paramDict keyEnumerator];
    id key;
    while ((key = [enumerator nextObject])) {
        NSCharacterSet *chatSet = [NSCharacterSet characterSetWithCharactersInString:@"!*'();:@&=+$,/?%#[]"];
        NSString *urlEnCodeStr = [[[paramDict objectForKey:key] description] stringByAddingPercentEncodingWithAllowedCharacters:chatSet];
        [paramsArray addObject:[NSString stringWithFormat:@"%@=%@", [key description], urlEnCodeStr]];
    }
    [result appendString:[paramsArray componentsJoinedByString:@"&"]];
    [result appendString:endString];
    return [self initWithString:result];
}

+ (id)URLWithFormat:(NSString *)format, ... {
	va_list arguments;
    va_start(arguments, format);
	NSString *string = [[NSString alloc] initWithFormat:format arguments:arguments];
	va_end(arguments);
	return [NSURL URLWithString:string];
}

@end
